package com.nmsl.statistic.utils;

import com.nmsl.statistic.constants.Constants;
import com.nmsl.statistic.domain.DailyFlow;
import com.nmsl.statistic.domain.TollManage;
import com.nmsl.statistic.mapper.DailyFlowMapper;
import org.springframework.data.redis.core.RedisTemplate;

import java.math.BigDecimal;

public class DailyFlowUtils {
//    支付： 增加金额  支付方式  应付金额 实付金额 优惠金额
public static void pay(DailyFlowMapper dailyFlowMapper, TollManage tollManage, RedisTemplate redisTemplate){

    Boolean flag  = true;
    while (flag){
        flag =! redisTemplate.opsForValue().setIfAbsent(Constants.DAILY_FLOW_VERSION, 1);
    }

    try {

        DailyFlow d = dailyFlowMapper.getDailyFlowByTime(TimeUtil.getcruntTime("YYYY-MM-dd"));

        d.setShoudAmount(d.getAmount().add(tollManage.getAmount()));
        BigDecimal bigDecimal = new BigDecimal(d.getDiscountAmount());
        BigDecimal dis = bigDecimal.add(tollManage.getShoudAmount().subtract(tollManage.getAmount()));
        d.setDiscountAmount(dis.toString());
        d.setAmount(tollManage.getAmount());
        d.setPlayAmount(d.getPlayAmount().add(tollManage.getAmount()));
        dailyFlowMapper.updateDailyFlow(d);
    }catch (Exception e){
        redisTemplate.delete(Constants.DAILY_FLOW_VERSION);
    }finally {
        redisTemplate.delete(Constants.DAILY_FLOW_VERSION);
    }





}
    public static void payCart(DailyFlowMapper dailyFlowMapper, TollManage tollManage, RedisTemplate redisTemplate){
        Boolean flag  = true;
        while (flag){
            flag =! redisTemplate.opsForValue().setIfAbsent(Constants.DAILY_FLOW_VERSION, 1);
        }
        try {
            DailyFlow d = dailyFlowMapper.getDailyFlowByTime(TimeUtil.getcruntTime("YYYY-MM-dd"));
            d.setShoudAmount(d.getAmount().add(tollManage.getAmount()));
            BigDecimal bigDecimal = new BigDecimal(d.getDiscountAmount());
            BigDecimal dis = bigDecimal.add(tollManage.getShoudAmount().subtract(tollManage.getShoudAmount()));
            d.setDiscountAmount(dis.toString());
            d.setCardAmount(d.getCardAmount().add(tollManage.getAmount()));
            dailyFlowMapper.updateDailyFlow(d);
        }catch (Exception e){
            redisTemplate.delete(Constants.DAILY_FLOW_VERSION);
        }finally {
            redisTemplate.delete(Constants.DAILY_FLOW_VERSION);
        }

    }
}
